package com.thirteen.app.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.thirteen.app.entity.User;

import java.util.Calendar;

public class JWTUtils {

    private static final String SING = "@#$!ERIC";

    /**
     * 生成token
     *
     * @param map
     * @return
     */
    public static String getToken(User user) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 60 * 60 * 24);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("userId", user.getUserId());
        builder.withClaim("roleId", user.getRoleId());

        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));

        return token;
    }

    /**
     * 学生认证
     *
     * @param token
     * @return
     */
    public static boolean studentVerify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SING)).build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("认证...");
            if ("0".equals(jwt.getClaim("roleId").asString())) {
                System.out.println("学生认证通过");
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 教师认证
     *
     * @param token
     * @return
     */
    public static boolean teacherVerify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SING)).build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("认证...");
            System.out.println(jwt.getClaim("roleId").asString());
            if ("1".equals(jwt.getClaim("roleId").asString())) {
                System.out.println("教师认证通过");
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 管理员认证
     *
     * @param token
     * @return
     */
    public static boolean adminVerify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SING)).build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("认证...");
            if ("2".equals(jwt.getClaim("roleId").asString())) {
                System.out.println("管理员认证通过");
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

}
